package com.im.service.fundPlan.smo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.util.StringUtil;
import com.im.MDA;
import com.im.service.common.smo.ICommonSMO;
import com.im.service.dto.BaseException;
import com.im.service.dto.FileUpload;
import com.im.service.dto.FundPlan;
import com.im.service.dto.FundSource;
import com.im.service.dto.PlanDeclareSet;
import com.im.service.dto.Staff;
import com.im.service.folderManage.dao.IFolderManageOperDAO;
import com.im.service.model.PlanGreenReqVo;
import com.im.service.planDeclareSet.smo.IPlanDeclareSetOperSMO;
import com.im.service.planDeclareSet.smo.IPlanDeclareSetQuerySMO;
import com.im.service.projectInfo.dao.IFundSourceOperDAO;
import com.im.service.projectInfo.dao.IFundSourceQueryDAO;
import com.im.util.DateUtil;
import com.im.util.JsonUtil;
import com.im.util.ListUtil;
import com.im.util.ReturnsUtil;
import com.im.viewmodel.fundPlan.FileVo;
import com.im.viewmodel.fundPlan.FundPlanDeclareSetAddReqVo;
import com.im.viewmodel.fundPlan.FundPlanListRespVo;

import net.sf.json.JSONObject;

/**
 * 资金计划管理 事务操作SMO
 * 
 * @author xuwb
 */
@Service
public class FundPlanManageOperSMOImpl implements IFundPlanManageOperSMO{

	private static final Logger logger = LogManager.getLogger(FundPlanManageOperSMOImpl.class);

	@Autowired
	private IFundSourceQueryDAO fundSourceQueryDAO;
    @Autowired
    private IPlanDeclareSetQuerySMO planDeclareSetQuerySMO;
	@Autowired
	private IFundPlanQuerySMO fundPlanQuerySMO;
	@Autowired
	private IFundPlanOperSMO fundPlanOperSMO;
	
	@Autowired
	private IPlanDeclareSetOperSMO planDeclareSetOperSMO;
	
	@Autowired
	private IFundSourceOperDAO fundSourceOperDAO;
	
	@Autowired
    private ICommonSMO commonSMO;
	@Autowired
	private IFolderManageOperDAO folderManageOperDAO;
	
	
	@Override
	public String addFundPlanDeclareSet(FundPlanDeclareSetAddReqVo addReqVo,HttpServletRequest request) throws Exception {
		String returnMsg = "";
		// 0.资金计划唯一校验
		String fundPlanCode = commonSMO.querySeq("T_FUND_PLAN");
		FundPlan retFundPlan = fundPlanQuerySMO.queryFundPlanByCode(fundPlanCode);
		if(retFundPlan != null){
			return "已经存在相同编码的资金计划！";
		}
		String fundPlanId = UUID.randomUUID().toString();
		String declareSetId = UUID.randomUUID().toString();
		
		// 1.计划申报设置
		PlanDeclareSet planDeclareSet = new PlanDeclareSet();
		planDeclareSet.setDeclareSetId(declareSetId);
		planDeclareSet.setDeclareSetName(addReqVo.getFundPlanName());
		planDeclareSet.setDeclareRelaType(MDA.DECLARE_RELA_TYPE_FUND_PLAN);
		planDeclareSet.setDeclareType("20");
		planDeclareSet.setDeclareRelaObj(fundPlanId);
		planDeclareSet.setEnterRequest("is null");//TODO 前端没有输入，数据库不能为空
		planDeclareSet.setStatusCd(MDA.PLAN_DECLARE_SET_STATUS_CD_OPEN.toString());
		planDeclareSet.setDocCode("is null");//TODO 前端没有输入，数据库不能为空
		planDeclareSetOperSMO.savePlanDeclareSet(planDeclareSet);
		
		// 2.资金计划
		FundPlan fundPlan = new FundPlan();
		fundPlan.setFundPlanId(fundPlanId);
		fundPlan.setFundPlanName(addReqVo.getFundPlanName());
		fundPlan.setFundPlanCode(fundPlanCode);
		fundPlan.setImpleProjId(addReqVo.getImpleProjId());
		fundPlan.setDeclareSetId(declareSetId);
		fundPlan.setStatusCd(addReqVo.getStatusCd());
		fundPlan.setDescription(addReqVo.getDescription());
		fundPlan.setCreateDt(new Date());
		fundPlan.setVersion(new Date());
		// 获取员工
		Object staffObj = request.getSession().getAttribute("loginedStaff");
		if (staffObj != null) {
			Staff staff = (Staff) staffObj;
			fundPlan.setApplicant(staff.getStaffId());
		}
		fundPlanOperSMO.saveFundPlan(fundPlan);
		
		return returnMsg;
	}



	@Override
	public String addFundPlan(FundPlanListRespVo reqVo) throws Exception {
		String errorMsg = "";
		// 1.更新资金计划
		Double total = reqVo.getFundSourceBu() + reqVo.getFundSourceGao() + reqVo.getFundSourceQi()
				+ reqVo.getFundSourceSheng() + reqVo.getFundSourceShi();
		reqVo.setTotal(BigDecimal.valueOf(total));
		String fundPlanId = UUID.randomUUID().toString();
		reqVo.setStatusCd(MDA.FUND_PLAN_STATUS_CD_WAIT.toString());
		FundPlan fundPlan = new FundPlan();
		fundPlan.setCreateDt(new Date());
		PropertyUtils.copyProperties(fundPlan, reqVo);
		fundPlan.setFundPlanId(fundPlanId);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("impleProjId", fundPlan.getImpleProjId());
		paramMap.put("declareSetId", fundPlan.getDeclareSetId());
		List<FundPlan> list  = fundPlanQuerySMO.queryFundPlanList(paramMap);
		if(list != null && list.size() > 0){
			return "该申报批次与项目已存在!";
		}
		fundPlanOperSMO.saveFundPlan(fundPlan);

		// 2.更新资金信息
		FundSource fundSource = new FundSource();
		fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_401);// 资金计划-填报数据
		fundSource.setFundSourceObj(fundPlanId);
		fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
		int num = 0;
		// 部补助
		if (reqVo.getFundSourceBu() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
			fundSource.setFundVal(reqVo.getFundSourceBu().toString());
			num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if (num == 0) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(fundPlan.getYearDt());
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}

		// 省财政
		if (reqVo.getFundSourceSheng() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
			fundSource.setFundVal(reqVo.getFundSourceSheng().toString());
			num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if (num == 0) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(fundPlan.getYearDt());
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 高速水运融资
		if (reqVo.getFundSourceGao() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
			fundSource.setFundVal(reqVo.getFundSourceGao().toString());
			num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if (num == 0) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(fundPlan.getYearDt());
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 市州配套
		if (reqVo.getFundSourceShi() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
			fundSource.setFundVal(reqVo.getFundSourceShi().toString());
			num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if (num == 0) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(fundPlan.getYearDt());
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 企业自筹
		if (reqVo.getFundSourceQi() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
			fundSource.setFundVal(reqVo.getFundSourceQi().toString());
			fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if (num == 0) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(fundPlan.getYearDt());
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 其他
		if (reqVo.getFundSourceOther() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_OTHER);
			fundSource.setFundVal(reqVo.getFundSourceOther().toString());
			fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if (num == 0) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(fundPlan.getYearDt());
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 下达文件入表
		uploadFileDeal(reqVo, "160", fundPlanId);
		return errorMsg;
	}

	public void uploadFileDeal(FundPlanListRespVo reqVo, String uploadObjType, String uploadObjId) {
		// 新增或修改添加文件处理
		List<FileVo> list = reqVo.getFiles();
		if (list == null || list.size() == 0) {
			list = reqVo.getAddFiles();
		}
		if (list != null) {
		for (int i = 0; i < list.size(); i++) {
			FileVo fileJson = list.get(i);
			String uploadName = fileJson.getAttachFullName();// attachFullName
			String fileSuffix = fileJson.getAttachSuffix();// attachSuffix
			String fileAttr = "10";
			String fileType = "10";
			String uploadSize = fileJson.getAttachSize();// attachSize
			String filePath = fileJson.getAttachPath();// attachPath
			String uploadDate = fileJson.getUploadDt();// uploadDt
			String uploadType = "";
			FileUpload fileUploadInfo = new FileUpload();
			if (!"".equals(fileSuffix)) {
				uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(fileSuffix.toLowerCase());
			}
			String uploadId = UUID.randomUUID().toString();
			fileUploadInfo.setUploadId(uploadId);
			fileUploadInfo.setUploadName(uploadName);
			fileUploadInfo.setUploadObjType(uploadObjType);
			fileUploadInfo.setUploadObjId(uploadObjId);
			fileUploadInfo.setUploadType(uploadType);
			fileUploadInfo.setFileSuffix(fileSuffix);
			fileUploadInfo.setFileAttr(fileAttr);
			fileUploadInfo.setFileType(fileType);
			fileUploadInfo.setUploadSize(Long.valueOf(uploadSize));
			fileUploadInfo.setFilePath(filePath);
			fileUploadInfo.setUploadDate(uploadDate);
			folderManageOperDAO.insertFileUploadInfo(fileUploadInfo);
			}
		}
		List<FileVo> dellist = reqVo.getDelFiles();
		if (dellist != null) {
			for (int i = 0; i < dellist.size(); i++) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("uploadId", dellist.get(i).getUploadId());
				folderManageOperDAO.delFileUpload(param);
			}
		}

	}
	@Override
	public void updateFundPlan(FundPlanListRespVo reqVo) throws Exception {
		// 1.更新资金计划
		Double total = reqVo.getFundSourceBu() + reqVo.getFundSourceGao()
				+ reqVo.getFundSourceQi() + reqVo.getFundSourceSheng() + reqVo.getFundSourceShi();
		reqVo.setTotal(BigDecimal.valueOf(total));
		reqVo.setFundPlanCode(null);//资金编码不修改
		reqVo.setStatusCd(MDA.FUND_PLAN_STATUS_CD_WAIT.toString());//待审核
		fundPlanOperSMO.updateFundPlan(reqVo);
		
		// 2.更新资金信息
		FundSource fundSource = new FundSource();
		fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_401);// 资金计划
		fundSource.setFundSourceObj(reqVo.getFundPlanId());
		fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
		int num = 0;
		// 部补助
		if (reqVo.getFundSourceBu() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
			fundSource.setFundVal(reqVo.getFundSourceBu().toString());
			num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if(num == 0){
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO 年度如何定
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		
		// 省财政
		if (reqVo.getFundSourceSheng() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
			fundSource.setFundVal(reqVo.getFundSourceSheng().toString());
			num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if(num == 0){
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO 年度如何定
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 高速水运融资
		if (reqVo.getFundSourceGao() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
			fundSource.setFundVal(reqVo.getFundSourceGao().toString());
			num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if(num == 0){
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO 年度如何定
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 市州配套
		if (reqVo.getFundSourceShi() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
			fundSource.setFundVal(reqVo.getFundSourceShi().toString());
			num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if(num == 0){
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO 年度如何定
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 企业自筹
		if (reqVo.getFundSourceQi() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
			fundSource.setFundVal(reqVo.getFundSourceQi().toString());
			fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if(num == 0){
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO 年度如何定
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		// 其他
		if (reqVo.getFundSourceOther() != null) {
			fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_OTHER);
			fundSource.setFundVal(reqVo.getFundSourceOther().toString());
			fundSourceOperDAO.updateFundSourceByObjId(fundSource);
			if (num == 0) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO
																						// 年度如何定
				fundSourceOperDAO.addFundSource(fundSource);
			}
		}
		uploadFileDeal(reqVo, "160", reqVo.getFundPlanId());
	}



	@Override
	public void deleteFundPlan(FundPlanListRespVo reqVo) throws Exception {
		// 1.更新资金计划
		fundPlanOperSMO.updateFundPlanForDel(reqVo);
		
		// 2.更新资金信息
		FundSource fundSource = new FundSource();
		fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND);// 资金计划
		fundSource.setFundSourceObj(reqVo.getFundPlanId());
		fundSource.setStatusCd(Integer.parseInt(MDA.INVALID_STATUS_CD));//失效
		fundSourceOperDAO.updateFundSource(fundSource);
	}

	@Override
	public void batchAuditFundPlan(FundPlanListRespVo reqVo) throws Exception {
		// 1.更新资金计划
		reqVo.setFundPlanCode(null);// 资金编码不修改
		fundPlanOperSMO.updateFundPlan(reqVo);
		List<String> planIds = reqVo.getFundPlanIds();
		String operType = reqVo.getOperType();
		for (int i = 0; i < planIds.size(); i++) {
			String fundPlanId = planIds.get(i);
			// 查询已填报或已初审资金
			FundSource fundSource = new FundSource();
			if (StringUtil.isNotEmpty(operType) && "firstAudit".equalsIgnoreCase(operType)) {// 初审去查401的数据
				fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_401);
			} else {// 批复去查402的数据
				fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_402);
			}
			fundSource.setFundSourceObj(fundPlanId);
			List<FundSource> fundSourceList = fundSourceQueryDAO.queryFoundSource(fundSource);
			for (FundSource fundSource2 : fundSourceList) {
				if (StringUtil.isNotEmpty(operType) && "firstAudit".equalsIgnoreCase(operType)) {
					fundSource2.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_402);
				} else {
					fundSource2.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_403);
				}
				fundSource2.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
				fundSource2.setFundSourceId(UUID.randomUUID().toString());
				fundSourceOperDAO.addFundSource(fundSource2);
			}
		}
	}

	@Override
	public void auditFundPlan(FundPlanListRespVo reqVo) throws Exception {
		// 1.更新资金计划
		reqVo.setFundPlanCode(null);//资金编码不修改
		fundPlanOperSMO.updateFundPlan(reqVo);
		FundSource fundSource = new FundSource();
		//初审时 允许修改资金
		if(StringUtil.isNotEmpty(reqVo.getOperType()) && "firstAudit".equalsIgnoreCase(reqVo.getOperType())){
			fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_402);
		} else {
			fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_403);
		}
		fundSource.setFundSourceObj(reqVo.getFundPlanId());
		fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
			int num = 0;
			// 部补助
			if (reqVo.getFundSourceBu() != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
				fundSource.setFundVal(reqVo.getFundSourceBu().toString());
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 省财政
			if (reqVo.getFundSourceSheng() != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
				fundSource.setFundVal(reqVo.getFundSourceSheng().toString());
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 高速水运融资
			if (reqVo.getFundSourceGao() != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
				fundSource.setFundVal(reqVo.getFundSourceGao().toString());
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 市州配套
			if (reqVo.getFundSourceShi() != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
				fundSource.setFundVal(reqVo.getFundSourceShi().toString());
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 企业自筹
			if (reqVo.getFundSourceQi() != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
				fundSource.setFundVal(reqVo.getFundSourceQi().toString());
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if(num == 0){
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}
			// 其他
			if (reqVo.getFundSourceOther() != null) {
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
				fundSource.setFundVal(reqVo.getFundSourceOther().toString());
				num = fundSourceOperDAO.updateFundSourceByObjId(fundSource);
				if (num == 0) {
					fundSource.setFundSourceId(UUID.randomUUID().toString());
					fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
					fundSourceOperDAO.addFundSource(fundSource);
				}
			}

		// 批复下达
		if(StringUtil.isNotEmpty(reqVo.getOperType()) && "finalAudit".equalsIgnoreCase(reqVo.getOperType())){
			uploadFileDeal(reqVo, "160", reqVo.getFundPlanId());
		}
	}



	@Override
	public String addFundPlanDeclareSet(String jsonStr, Staff staff) throws Exception {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(
					new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		String errorMsg = "获取新增资金计划申报设置入参时：";
		// 2.获取入参 资金计划申报信息
		String fundPlanName = JsonUtil.getNotNullStringFromJSON(jsonObj, "fundPlanName", errorMsg);
		String enterRequest = JsonUtil.getNotNullStringFromJSON(jsonObj, "enterRequest", errorMsg);
		String statusCd = JsonUtil.getNotNullStringFromJSON(jsonObj, "statusCd", errorMsg);
		String yearDt = JsonUtil.getNotNullStringFromJSON(jsonObj, "yearDt", errorMsg);
		String endDt = JsonUtil.getNotNullStringFromJSON(jsonObj, "endDt", errorMsg);
		String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);
		String docCode = JsonUtil.getNotNullStringFromJSON(jsonObj, "docCode", errorMsg);
		String fundPlanCode = JsonUtil.getNotNullStringFromJSON(jsonObj, "fundPlanCode", errorMsg);

		PlanDeclareSet fundPlanSet = new PlanDeclareSet();

		String declareSetId = UUID.randomUUID().toString();
		String fundPlanId = UUID.randomUUID().toString();
		fundPlanSet.setDeclareSetId(declareSetId);
		fundPlanSet.setDeclareSetName(fundPlanName);
		fundPlanSet.setDeclareCode(fundPlanCode);
		fundPlanSet.setDeclareRelaObj(fundPlanId);
		fundPlanSet.setDescription(description);
		fundPlanSet.setEnterRequest(enterRequest);
		fundPlanSet.setYearDt(yearDt);
		fundPlanSet.setEndDt(endDt);
		fundPlanSet.setDocCode(docCode);
		fundPlanSet.setDeclareType("20");
		fundPlanSet.setStatusCd(statusCd);
		fundPlanSet.setDeclareRelaType(MDA.DECLARE_RELA_TYPE_FUND_PLAN);
		planDeclareSetOperSMO.savePlanDeclareSet(fundPlanSet);
	
		
		// // 2.资金计划
		// FundPlan fundPlan = new FundPlan();
		// fundPlan.setFundPlanId(fundPlanId);
		// fundPlan.setFundPlanName(fundPlanName);
		// fundPlan.setImpleProjId(impleProjId);
		// fundPlan.setDeclareSetId(declareSetId);
		// fundPlan.setFundPlanCode(fundPlanCode);
		// fundPlan.setApplicant(staff.getStaffId());
		// if(MDA.FUND_PLAN_STATUS_CD_WRITE.equals(Integer.valueOf(statusCd))){
		// fundPlan.setStatusCd(MDA.FUND_PLAN_STATUS_CD_WRITE.toString());
		// }else{
		// fundPlan.setStatusCd(MDA.FUND_PLAN_STATUS_CD_APPLY.toString());
		// }
		// fundPlanOperSMO.saveFundPlan(fundPlan);
		
		return ReturnsUtil.returnSuccess(new JSONObject()).toString();
	}



	@Override
	public String updateFundPlanDeclareSet(String jsonStr) {
		try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(jsonStr)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
			}
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取修改资金计划申报设置入参时：";

			//如果是批量处理
			List<String> declareSetIds = new ArrayList<>();
			if(jsonObj.containsKey("declareSetIds")){
				declareSetIds = jsonObj.getJSONArray("declareSetIds");
			}
			String statusCd = JsonUtil.getStringFromJSON(jsonObj, "statusCd", errorMsg);

			if(declareSetIds != null && declareSetIds.size() > 0){

				for(String declareSetId : declareSetIds){

					PlanDeclareSet fundPlanSet = new PlanDeclareSet();
					fundPlanSet.setDeclareSetId(declareSetId);
					fundPlanSet.setStatusCd(statusCd);

					planDeclareSetOperSMO.updateFundPlanSet(fundPlanSet);
				}

				return ReturnsUtil.returnSuccess(new JSONObject()).toString();
			}

			// 2.获取入参 资金计划申报信息
			String declareSetId = JsonUtil.getStringFromJSON(jsonObj, "declareSetId", errorMsg);
			String fundPlanId = JsonUtil.getStringFromJSON(jsonObj, "fundPlanId", errorMsg);
			String fundPlanName = JsonUtil.getStringFromJSON(jsonObj, "fundPlanName", errorMsg);
			String impleProjId = JsonUtil.getStringFromJSON(jsonObj, "impleProjId", errorMsg);
			String yearDt = JsonUtil.getNotNullStringFromJSON(jsonObj, "yearDt", errorMsg);
			String endDt = JsonUtil.getNotNullStringFromJSON(jsonObj, "endDt", errorMsg);
			String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);
			String docCode = JsonUtil.getStringFromJSON(jsonObj, "docCode", errorMsg);
			String enterRequest = JsonUtil.getStringFromJSON(jsonObj, "enterRequest", errorMsg);
			
			PlanDeclareSet fundPlanSet = new PlanDeclareSet();
			fundPlanSet.setDeclareSetId(declareSetId);
			fundPlanSet.setDeclareSetName(fundPlanName);
			fundPlanSet.setEnterRequest(enterRequest);
			fundPlanSet.setDocCode(docCode);
			fundPlanSet.setStatusCd(statusCd);
			fundPlanSet.setYearDt(yearDt);
			fundPlanSet.setEndDt(endDt);
			fundPlanSet.setDescription(description);
			
			planDeclareSetOperSMO.updateFundPlanSet(fundPlanSet);
			
			if (!MDA.DECLAE_SET_DOC_CANCEL.equals(statusCd)) {
				FundPlan inPlan = new FundPlan();
				inPlan.setFundPlanId(fundPlanId);
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("fundPlan", inPlan);
				FundPlan fundPlan = fundPlanQuerySMO.queryFundPlanDetail(paramMap);
				if(fundPlan != null){
					String fundPlanStatusCd = fundPlan.getStatusCd();
						if (MDA.FUND_PLAN_STATUS_CD_APPLY.toString().equals(fundPlanStatusCd)
							|| MDA.FUND_PLAN_STATUS_CD_WRITE.toString().equals(fundPlanStatusCd)){
						FundPlan iPlan = new FundPlan();
							iPlan.setFundPlanId(fundPlanId);
						iPlan.setFundPlanName(fundPlanName);
						iPlan.setDeclareSetId(declareSetId);
							iPlan.setStatusCd(statusCd);
						iPlan.setImpleProjId(impleProjId);
						fundPlanOperSMO.updatefundPlanForSet(iPlan);
					}else{
						return ReturnsUtil.returnFailure("当前资金计划状态不允许修改资金计划设置！");
					}
				}else{
					return ReturnsUtil.returnFailure("没有找到对应的资金计划！");
				}
			} else {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("declareSetId", declareSetId);
				fundPlanOperSMO.deletefundPlan(paramMap);
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
		}
	}
	
	
	/*
	@Override
	public Map<String,Object> saveFundPlanSetInfo(String jsonStr) throws Exception{
		
		JSONObject jo = JSONObject.fromObject(jsonStr);
		Map<String,Object> retMap = new HashMap<String,Object>();
		
		// 保存  planDeclareSet
		String fundPlanName = JsonUtil.getNotNullStringFromJSON(jo,"fundPlanName","解析");
		//String enterRequest = JsonUtil.getNotNullStringFromJSON(jo,"enterRequest","解析");
		String docCode = JsonUtil.getNotNullStringFromJSON(jo,"statusCd","解析");
		String description = JsonUtil.getStringFromJSON(jo,"description","解析");
		String fundPlanId = JsonUtil.getNotNullStringFromJSON(jo,"fundPlanId","解析");
		String impleProjId = JsonUtil.getNotNullStringFromJSON(jo,"impleProjId","解析");
		
		
		// 判断资金计划是否已经存在
		FundPlan retFundPlan = fundPlanQuerySMO.queryFundPlan(fundPlanId);
		if(retFundPlan != null){
			throw new Exception("已经存在相同编码的资金计划！");
		}
		
		
		PlanDeclareSet pds = new PlanDeclareSet();
		String declareSetId = UUID.randomUUID().toString();
		pds.setDeclareSetName(fundPlanName);
		pds.setDeclareType("1");
		pds.setEnterRequest(" this is null");
		pds.setStatusCd(MDA.FUND_PLAN_STATUS_CD_APPLY);
		pds.setDocCode(docCode);
		pds.setDescription(description);
		pds.setDeclareSetId(declareSetId);
		pds.setCreateDt(new Date());
		pds.setDeclareRelaType(MDA.DECLARE_RELA_TYPE_FUND_PLAN);
		pds.setDeclareRelaObj(fundPlanId);
		planDeclareSetOperSMO.savePlanDeclareSet(pds);
		
		FundPlan fp = new FundPlan();
		fp.setDeclareSetId(declareSetId);
		fp.setFundPlanId(fundPlanId);
		fp.setFundPlanName(fundPlanName);
		fp.setImpleProjId(impleProjId);
		fp.setStatusCd(MDA.FUND_PLAN_STATUS_CD_APPLY);
		fp.setDocCode(docCode);
		fp.setCreateDt(new Date());
		fundPlanOperSMO.saveFundPlan(fp);
		
		retMap.put("retCode", "0");
		retMap.put("retMsg", "success");
		return retMap;
	}*/

	@Override
	public String updateFundPlanDeclareSetByCondition(String jsonStr) {
		try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(jsonStr)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
			}
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取修改资金计划申报设置入参时：";

			// 2.获取入参 资金计划申报信息
			List<String> declareSetIds = jsonObj.getJSONArray("declareSetIds");
			String statusCd = JsonUtil.getStringFromJSON(jsonObj, "statusCd", errorMsg);
			if(!ListUtil.isListEmpty(declareSetIds)){
				for(String declareSetId:declareSetIds){
					PlanDeclareSet fundPlanSet = new PlanDeclareSet();
					fundPlanSet.setDeclareSetId(declareSetId);
					fundPlanSet.setStatusCd(statusCd);
					planDeclareSetOperSMO.updateFundPlanSet(fundPlanSet);
				}
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.toString());
		}
	}

    public String addFundPlanGreen(String jsonStr) {

        // 获取参数 各项金额，实施项目，建设单位，申报计划
        PlanGreenReqVo reqVo = JsonUtil.jsonToBean(jsonStr, PlanGreenReqVo.class);

        // 取 申报计划id
        String declareSetId = reqVo.getDeclareSetId();
        PlanDeclareSet planDeclareSet = planDeclareSetQuerySMO.queryPlanDeclareSet(declareSetId);
        // 回填 T_INVEST_PLAN 表，改状态
        String planId = planDeclareSet.getDeclareRelaObj();
        // 查询 T_INVEST_PLAN 是否存在，存在则改状态，不存在，则增加
        FundPlan fundPlan = fundPlanQuerySMO.queryFundPlan(planId);
        try {
            if(fundPlan!=null){
                fundPlan.setStatusCd(reqVo.getStatusCd());
                fundPlan.setVersion(new Date());
                fundPlanOperSMO.updatefundPlanForSet(fundPlan);

                // 保存数据至 T_Fund_Source 表  FUND_SOURCE_OBJ_TYPE = 303
                addFundSourceForPlan(reqVo,planId,MDA.FUND_SOURCE_OBJ_TYPE_INVEST_303);
            } else {

                // 4.新增投资计划
                fundPlan = new FundPlan();
                fundPlan.setDeclareSetId(declareSetId);
                fundPlan.setFundPlanId(planId);
                fundPlan.setFundPlanName(planDeclareSet.getDeclareSetName()+"-绿色审批");
                fundPlan.setImpleProjId(reqVo.getImpleProjId());

                //MDA.FUND_PLAN_STATUS_CD_PASS.toString()
                fundPlan.setStatusCd(reqVo.getStatusCd());
                fundPlan.setApplicant(reqVo.getStaffId());

                String investPlanCode="";
                investPlanCode = commonSMO.querySeq("T_FUND_PLAN");
                fundPlan.setFundPlanCode(investPlanCode);
                fundPlan.setDescription(reqVo.getRemark()+"-绿色审批");
				// fundPlan.setYearDt(DateUtil.getNowDefault().substring(0,4));
                fundPlan.setCreateDt(new Date());
                fundPlanOperSMO.saveFundPlan(fundPlan);

                // 保存数据至 T_Fund_Source 表  FUND_SOURCE_OBJ_TYPE = 303
                addFundSourceForPlan(reqVo,planId,MDA.FUND_SOURCE_OBJ_TYPE_INVEST_301);
                addFundSourceForPlan(reqVo,planId,MDA.FUND_SOURCE_OBJ_TYPE_INVEST_302);
                addFundSourceForPlan(reqVo,planId,MDA.FUND_SOURCE_OBJ_TYPE_INVEST_303);
            }
        } catch (Exception e){
            e.getStackTrace();
        }
        // 下达文件入表
        FundPlanListRespVo vo = new FundPlanListRespVo();
        BeanUtils.copyProperties(reqVo,vo);
        uploadFileDeal(vo, "160", planId);
        return ReturnsUtil.returnSuccess(new JSONObject()).toString();
    }


    public void addFundSourceForPlan(PlanGreenReqVo reqVo,String objId,String objType){

        FundSource fundSource = new FundSource();
        fundSource.setFundSourceObjType(objType);
        fundSource.setFundSourceObj(objId);
        fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
        fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO
        // 部补助
        if (StringUtil.isNotEmpty(reqVo.getBuFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
            fundSource.setFundVal(reqVo.getBuFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 省财政
        if (StringUtil.isNotEmpty(reqVo.getShengFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
            fundSource.setFundVal(reqVo.getShengFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 高速水运融资
        if (StringUtil.isNotEmpty(reqVo.getGaoFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
            fundSource.setFundVal(reqVo.getGaoFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 市州配套
        if (StringUtil.isNotEmpty(reqVo.getShiFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
            fundSource.setFundVal(reqVo.getShiFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 企业自筹
        if (StringUtil.isNotEmpty(reqVo.getQiFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
            fundSource.setFundVal(reqVo.getQiFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
        // 其他
        if (StringUtil.isNotEmpty(reqVo.getOtherFund())) {
            fundSource.setFundSourceId(UUID.randomUUID().toString());
            fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_OTHER);
            fundSource.setFundVal(reqVo.getOtherFund());
            fundSourceOperDAO.addFundSource(fundSource);
        }
    }
}
